/*
* @overview: 
* @Author: wgf 
* @Date: 2024-05-24 16:02:27 
*/

import 'package:get/get.dart';
import 'package:rc_widget/rc_widget.dart';

import 'package:flutter_study/models/user_model.dart';
import 'package:flutter_study/models/message_model.dart';

import '../base/app_getx_controller.dart';

class AppUserController extends AppGetxController {
  static AppUserController get to => Get.find<AppUserController>();

  final RxBool _loginStatus = false.obs;
  final Rx<UserData> _userData = UserData.init().obs;

  bool get isLogin => _loginStatus.value;

  /// uid
  String get uid => _userData.value.uid;

  /// 用户账号
  String get username => _userData.value.username;

  /// 用户昵称
  String get nickname => _userData.value.nickName;

  /// 用户头像
  String get avatar => _userData.value.avatarUrl;

  /// 是否绑定google验证器
  bool get isBoundGoogle => _userData.value.googleStatus == 1;

  /// 实名状态
  int get realNameStatus => _userData.value.isRealName;

  /// 邀请码
  String get inviteCode => _userData.value.code;

  String get unit => _userData.value.unit;

  /// 获取用户信息
  Future<void> getUserInfo() async {
    const String url = '/api/user_info';

    final result = await RcHttp.get<UserResponseModel>(
      url,
      cancelToken: cancelToken,
      errorJson: UserResponseModel.init,
      fromJson: UserResponseModel.fromJson,
    );

    if (result.code == 200) {
      _userData.value = result.data;
    }
  }

  /// 切换登录状态
  Future<void> toggleLoginStatus([bool? value]) async {
    if (value == null) {
      _loginStatus.value = !_loginStatus.value;
    } else {
      _loginStatus.value = value;
    }
  }

  /// 检查token是否可用
  Future<void> checkToken() async {
    const String url = '/api/tool/token';

    final data = {
      'token': await RcStorage.getString(RcStorageKey.token),
    };

    final result = await RcHttp.post<MessageResponseModel>(
      url,
      data: data,
      cancelToken: cancelToken,
      errorJson: MessageResponseModel.init,
      fromJson: MessageResponseModel.fromJson,
    );

    if (result.code == 200) {
      getUserInfo();
      toggleLoginStatus(true);
    }
  }

  /// 退登
  Future<void> logout() async {
    toggleLoginStatus(false);
    RcStorage.remove(RcStorageKey.token);

    Get.offAllNamed('/account_home');
  }
}
